package com.encryption.rpc;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.encryption.dao.Condition;
import com.encryption.logic.ManageActionConstant;
import com.encryption.logic.ManageActionLogHelper;
import com.encryption.logic.SendRandomHelper;
import com.encryption.logic.UserConstant;
import com.encryption.logic.UserDefaultPsdHelper;
import com.encryption.logic.UserLoginLock;
import com.encryption.model.User;
import com.encryption.rpc.model.LoginErrorInfo;
import com.encryption.rpc.model.SessionConstant;
import com.encryption.rpc.model.UserRegisterStatusEnum;
import com.encryption.rpc.model.WrapperPageInfo;
import com.encryption.service.UserService;
import com.encryption.service.ca.CertQueryFacade;
import com.encryption.service.ca.identify.CertificateIdentifyService;
import com.encryption.service.ca.identify.impl.CertificateIdentifyServiceImpl;
import com.encryption.service.ca.impl.CertQueryFacadeImpl;
import com.encryption.service.ca.util.CryptoUtil;
import com.encryption.service.impl.UserServiceImpl;
import com.encryption.service.qrc.impl.DocEncryptHandlerImpl;
import com.encryption.util.SessionUtil;
import com.encryption.util.TestUseUtil;

import flex.messaging.FlexContext;

public class UserFacade {
	private UserService userService = UserServiceImpl.getUserServiceImpl();
	private CertQueryFacade certFacade = new CertQueryFacadeImpl();
	private CertificateIdentifyService identifyservice = new CertificateIdentifyServiceImpl();

	public Object login(String loginName, String password) {
		String ipAddr = FlexContext.getHttpRequest().getRemoteAddr();

		boolean isLock = UserLoginLock.isLocked(ipAddr);
		if (isLock) {
			return LoginErrorInfo.createLockObject();
		}

		User user = userService.getUserByLoginName(loginName);
		if (user != null
				&& user.getAduitState() != UserConstant.STATE_DELETE
				&& (user.getPassword().equals(password) || user.getPassword()
						.equals(CryptoUtil.md5(password)))) {
			user.setLastLogin(new Date());
			userService.updateUser(user);

			boolean isApplyCert = certFacade.isApplyCert(user.getId() + "");
			user.setApplyCert(isApplyCert);
			UserLoginLock.unLock(ipAddr);
			if (user.getRole() == UserConstant.ROLE_MANAGE)
				ManageActionLogHelper.addLog(ManageActionConstant.ACTION_LOGIN,
						"");
			return user;
		} else {
			UserLoginLock.addErrorTime(ipAddr);
			isLock = UserLoginLock.isLocked(ipAddr);
			if (isLock) {
				return LoginErrorInfo.createLockObject();
			}
		}

		return LoginErrorInfo.createErrorTimeObject(UserLoginLock
				.getLostErrorTime(ipAddr));
	}

	/**
	 * 0代表需要审核，1代表审核通过，2代表审核不通过
	 * 
	 * @param isPass
	 *            审核是否通过
	 * @param userId
	 *            用户ID
	 * @return
	 */
	public User processRegister(Boolean isPass, int userId) {
		User user = new User();
		user.setId(userId);
		user.setAduitState(isPass ? Integer
				.valueOf(UserRegisterStatusEnum.THROUGH_THE_AUDIT.getStatus())
				: Integer.valueOf(UserRegisterStatusEnum.UNTHROUGH_THE_AUDIT
						.getStatus()));
		userService.updateUser(user);
		return user;
	}

	/**
	 * 获取未审核过的用户列表
	 * 
	 * @return
	 */
	public List<User> getUnThroughAuditUser() {
		Condition cond = new Condition();
		cond.setCode("audit_state");
		cond.setOperation(Condition.EQ);
		cond.setValue(Integer.valueOf(UserRegisterStatusEnum.NEED_AUDIT
				.getStatus()));
		List<Condition> condList = new ArrayList<Condition>();
		condList.add(cond);
		return userService.getUserByCondition(condList);
	}

	public void logout() {
		SessionUtil.removeAttribute(SessionConstant.SESSION_USERID);
	}

	public User getByLoginName(String loginName) {
		User user = userService.getUserByLoginName(loginName);
		return user;
	}

	public int addUser(User user) {
		if (user.getAduitState() == 1)
			ManageActionLogHelper.addLog(ManageActionConstant.ACTION_ADD_USER,
					user.toString());

		Date date = new Date();
		user.setRegisterTime(date);
		user.setLastLogin(date);
		user.setRole(2);
		if (user.getPassword() == null || "".equals(user.getPassword())) {
			user.setPassword(UserDefaultPsdHelper.getMd5DefaultPsd());
		} else {
			user.setPassword(CryptoUtil.md5(user.getPassword()));
		}

		return userService.addUser(user);
	}

	public void updateUser(User user) {
		User newUser = user.cloneItem();
		userService.updateUser(newUser);
	}

	public void initUserPassword(User user) {
		user.setPassword(UserDefaultPsdHelper.getMd5DefaultPsd());

		ManageActionLogHelper.addLog(ManageActionConstant.ACTION_INIT_PASSWORD,
				user.toString());
		updateUser(user);
	}

	public String getDefAndMd5Psd() {
		return UserDefaultPsdHelper.getDefaultPassword() + ","
				+ UserDefaultPsdHelper.getMd5DefaultPsd();
	}

	public void auditUser(User user) {
		updateUser(user);
		// MailSend.sendTextMail(user.getEmail(), "审核通过", user.getLoginName()
		// + "已经审核通过");
	}

	public User sendUserRandom(String username) {
		User user = userService.getUserByLoginName(username);
		if (user == null)
			return null;

		sendRandom(user);
		return user;
	}

	public String changePassword(User user, String oldPsd, String password) {
		if(password != null){
			String md5Psd = CryptoUtil.md5(oldPsd);
			if(!user.getPassword().equals(md5Psd))
				return "原密码不正确";
		}else{
			password = oldPsd;
		}
		
		User cacheUser = user.cloneItem();
		cacheUser.setPassword(CryptoUtil.md5(password));
		userService.updateUser(cacheUser);
		return "";
	}

	public void sendRandom(User user) {
		SendRandomHelper.send(user);
	}

	public boolean randomValidate(User user, String random) {
		return SendRandomHelper.validate(user, random);
	}

	public List<User> getUserByDept(int dept) {
		Condition cond = new Condition();
		cond.setCode("department");
		cond.setOperation(Condition.EQ);
		cond.setValue(dept);
		List<Condition> condList = new ArrayList<Condition>();
		condList.add(cond);

		return userService.getUserByCondition(condList);
	}

	public void deleteUser(int userId) {
		userService.deleteUser(userId + "");
	}

	public List<User> getUserByCondition(List<Condition> condList) {
		return userService.getUserByCondition(condList);
	}

	public WrapperPageInfo getUserPagingByCondition(List<Condition> condList,
			int page, int pageSize) {
		List<User> userList = userService.getUserPagingByCondition(condList,
				page, pageSize);
		int recordCount = userService.getUserCountByCondition(condList);
		int allPageCount = (int) Math.ceil(((double) recordCount) / pageSize);
		WrapperPageInfo wraper = new WrapperPageInfo();
		wraper.setDataList(userList);
		wraper.setAllPageCount(allPageCount);
		wraper.setCurrentPage(page);
		wraper.setPageSize(pageSize);
		wraper.setRecordCount(recordCount);

		return wraper;
	}

	public String getCSRCmd() {
		return certFacade.getCSRCmd();
	}

	public String setInstallCmd(User user, String csr) {
		return certFacade.getInstallCmd(user, csr).replaceAll("\r", "")
				.replaceAll("\n", "");
	}

	public String getLogonCmd(int userId) {
		String uuid = UUID.randomUUID().toString();
		SessionUtil.setAttribute(SessionConstant.SESSION_RANDOM, uuid);
		return certFacade.getLogonCmd(userId + "", uuid);
	}

	public String verifyCert(int userId, String signedData) {
		Object randomObj = SessionUtil
				.getAttribute(SessionConstant.SESSION_RANDOM);
		String random = randomObj != null ? randomObj.toString() : "";
		String message = identifyservice
				.verify(userId + "", signedData, random);
		if ("success".equals(message)) {
			SessionUtil.setAttribute(SessionConstant.SESSION_CERT_STATE, 1);
		}
		return message;
	}

	public User getUserById(int userId) {
		return userService.getUserById(userId);
	}

	public int isActivition() {
		boolean isReg = new DocEncryptHandlerImpl().isReg();
		if (isReg)
			return 1;

		boolean isTest = TestUseUtil.isTest();
		return isTest ? 2 : 0;
	}

	public boolean activite(String companyName, String code) {
		boolean reg = new DocEncryptHandlerImpl().reg(companyName, code);
		return reg;
	}

	public static void main(String[] args) {
		System.out.println("C\\:\\Program\\ Files\\OpenOffice.org\\ 3");
	}
}
